<template>
  <div>
    <!-- 面包屑导航区域 -->
    <breadcrumb :breadcrumbs="breadcrumbs" />
    <el-card>
      <!-- 警告提示 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数！ "
        type="warning"
        :closable="false"
      >
      </el-alert>

      <!--选择商品分类区域  -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable=""
                  @close="handleClose(i, scope.row)"
                  >{{ item }}
                </el-tag>

                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialogClick(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParam(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >
            添加属性
          </el-button>
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable=""
                  @close="handleClose(i, scope.row)"
                  >{{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialogClick(scope.row.attr_id)"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParam(scope.row.attr_id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑参数 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsClick">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/Breadcrumb";
import { getCategories } from "@/network/goods/cate";
import {
  getCateParams,
  addParams,
  getParamById,
  editParamter,
  deleteParamter,
} from "@/network/goods/params";
export default {
  name: "Params",
  data() {
    return {
      breadcrumbs: ["商品管理", "参数列表"],
      cateList: [],
      //级联选择器的配置
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selectKeys: [], //级联选择框双向绑定的数组
      activeName: "many", //被激活的页签的名称
      manyTableData: [], //动态属性的数据
      onlyTableData: [], //静态属性的数据
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      editForm: {
        attr_name: "",
      },
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  components: {
    Breadcrumb,
  },
  methods: {
    //获取所有分类列表
    getCateList() {
      getCategories(3, 1, 10000).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取商品分类列表失败！" + res.meta.msg);
        this.cateList = res.data.result;
      });
    },
    //获取参数的列表数据
    getParamsData() {
      //验证选中的是否是3级分类
      if (this.selectKeys.length != 3) {
        this.selectKeys = [];
        this.manyTableData = this.onlyTableData = []; //清空表格
        return;
      }
      getCateParams(this.cateId, this.activeName)
        .then((res) => {
          if (res.meta.status != 200)
            return this.$message.error("获取参数列表失败！" + res.meta.msg);
          this.$message.success("获取参数列表成功！");

          res.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];

            //控制文本框的显示与隐藏
            item.inputVisible = false;
            //文本框中注入的值
            item.inputValue = "";
          });
          console.log(res.data);
          if (this.activeName == "many") this.manyTableData = res.data;
          else this.onlyTableData = res.data;
        })
        .catch((error) => {
          return this.$message.error("获取参数列表失败！" + error);
        });
    },
    //选择器选中事件处理
    handleChange() {
      this.getParamsData();
    },

    //页签点击事件的函数
    handleTabClick() {
      this.getParamsData();
    },
    //监听添加对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.addDialogVisible = false;
    },
    //添加参数
    addParamsClick() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;

        addParams(this.cateId, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
        })
          .then((res) => {
            if (res.meta.status != 201)
              return this.$message.error("添加参数失败！" + res.meta.msg);

            this.$message.success("添加成功！");
            this.addDialogVisible = false;
            this.getParamsData();
          })
          .catch((error) => {
            return this.$message.error("添加参数发生错误！" + error);
          });
      });
    },
    //监听编辑对话框关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
      this.editDialogVisible = false;
    },
    //编辑参数对话框
    showEditDialogClick(attrId) {
      this.editDialogVisible = true;

      //根据id查询当前参数信息
      getParamById(this.cateId, attrId, this.activeName).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("获取参数信息失败！" + res.meta.msg);
        this.editForm = res.data;
      });
    },
    //编辑参数确定
    editParamsClick() {
      editParamter(this.cateId, this.editForm.attr_id, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.activeName,
      })
        .then((res) => {
          if (res.meta.status != 200)
            return this.$message.error("更新参数信息失败！" + res.meta.msg);

          this.$message.success("更新成功！");
          this.editDialogVisible = false;
          this.getParamsData();
        })
        .catch((error) => {
          return this.$message.error("编辑参数发生错误！" + error);
        });
    },

    //删除参数
    removeParam(attrId) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteParamter(this.cateId, attrId).then((res) => {
            if (res.meta.status != 200)
              return this.$message.error("删除失败！" + res.meta.msg);
            this.$message.success("删除成功");
            this.getParamsData();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除！");
        });
    },
    //newtag处理事件
    handleInputConfirm(paramter) {
      if (paramter.inputValue.trim().length === 0) {
        paramter.inputValue = "";
        paramter.inputVisible = false;
        return;
      }
      paramter.attr_vals.push(paramter.inputValue.trim());
      paramter.inputValue = "";
      paramter.inputVisible = false;
      this.saveAttrvals(paramter);
    },
    //点击按钮展示文本输入框
    showInput(paramter) {
      paramter.inputVisible = true;

      //让文本框自动获得焦点
      //$nextTick方法作用：当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除标签
    handleClose(i, paramter) {
      paramter.attr_vals.splice(i, 1);
      this.saveAttrvals(paramter);
    },

    //保存参数
    saveAttrvals(paramter) {
      editParamter(this.cateId, paramter.attr_id, {
        attr_name: paramter.attr_name,
        attr_sel: this.activeName,
        attr_vals: paramter.attr_vals.join(","),
      }).then((res) => {
        if (res.meta.status != 200)
          return this.$message.error("修改参数项失败！" + res.meta.msg);

        this.$message.success("更新成功！");
      });
    },
  },
  computed: {
    //验证是否选中三级分类
    isBtnDisabled() {
      return this.selectKeys.length != 3;
    },
    cateId() {
      if (this.selectKeys.length == 3) return this.selectKeys[2];
      return null;
    },
    //动态计算·
    titleText() {
      if (this.activeName == "many") return "动态参数";
      else return "静态属性";
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>